const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://app/jsmodules/ArrayConverter.jsm");
Cu.import("resource://app/jsmodules/sbProperties.jsm");

var ourDisplayPane = null;

var gBundle = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
var strings = gBundle.createBundle("chrome://lyricmaster/locale/overlay.properties");

var bigyes = strings.GetStringFromName("bigyes");
var asktosave = strings.GetStringFromName("asktosave");
var lyrnotfound = strings.GetStringFromName("lyrnotfound");
var websearch = strings.GetStringFromName("websearch");
var posNotifs = strings.GetStringFromName("posNotifs");
var clktoSus = strings.GetStringFromName("clktoSus");
var negNotifs = strings.GetStringFromName("negNotifs");
var clktoEnab = strings.GetStringFromName("clktoEnab");

var curMediaItem = null;


if (typeof(SBProperties) == "undefined") {
	Cu.import("resource://app/jsmodules/sbProperties.jsm");
	if (!SBProperties)
		throw new Error("Failed to import sbProperties.jsm");
}

if (typeof(gMM) == "undefined")
    var gMM = Cc["@songbirdnest.com/Songbird/Mediacore/Manager;1"]
             .getService(Ci.sbIMediacoreManager);

var searchURL = "";

var lm_CSS = "";
var lm_dispAlbum = "";
var lm_dispTrack = "";
var lm_dispArtist = "";
var lm_noLyrFound = "";
var lm_saveLyrics = "";
var lm_webLoc = "";
var lm_libStyle = "";
var lm_showNotifs = "";

/*
 * Function invoked by the display pane manager to populate the display pane
 * menu.
 */
function onDisplayPaneMenuPopup(command, menupopup, doc) {
  switch (command) {
    case "create":
      var notifEnabledMenu = doc.createElement("menuitem");
      notifEnabledMenu.setAttribute("label", posNotifs);
      notifEnabledMenu.setAttribute("type", "radio");
      notifEnabledMenu.addEventListener("command", LM_enableNotifications,
                                        false);
      menupopup.appendChild(notifEnabledMenu);
      
      var notifDisabledMenu = doc.createElement("menuitem");
      notifDisabledMenu.setAttribute("label", negNotifs);
      notifDisabledMenu.setAttribute("type", "radio");
      notifDisabledMenu.addEventListener("command", LM_disableNotifications,
                                        false);
      menupopup.appendChild(notifDisabledMenu);

      if (prefs.getBoolPref("showNotifs"))
        notifEnabledMenu.setAttribute("checked", "true");
      else
        notifDisabledMenu.setAttribute("checked", "true");

      Lyricmaster.PaneController._menuPopup = menupopup;
      break;
    case "destroy":
      while (Lyricmaster.PaneController._menuPopup.firstChild)
        Lyricmaster.PaneController._menuPopup.removeChild(
            Lyricmaster.PaneController._menuPopup.firstChild);
      break;
    default:
      break;
  }
}
 
// Make a namespace.
if (typeof Lyricmaster == 'undefined') {
  var Lyricmaster = {};
}

//var mainDoc = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("Songbird:Main").window.document;

if (typeof(gBrowser) == "undefined")
	var gBrowser = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("Songbird:Main").window.gBrowser;

var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.lyricmaster.");
prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);

function LM_enableNotifications() {
  prefs.setBoolPref("showNotifs", true);
  document.getElementById("notifEnabledMenuItem").setAttribute("checked",
                                                               "true");
  document.getElementById("notifDisabledMenuItem").setAttribute("checked",
                                                                "false");
}

function LM_disableNotifications() {
  prefs.setBoolPref("showNotifs", false);
  document.getElementById("notifEnabledMenuItem").setAttribute("checked",
                                                               "false");
  document.getElementById("notifDisabledMenuItem").setAttribute("checked",
                                                                "true");
}

function LM_setBTNcontent()
{
  lm_showNotifs = prefs.getBoolPref("showNotifs");
  lm_showNotifs = !lm_showNotifs;
  prefs.setBoolPref("showNotifs", lm_showNotifs);
}

function setPrefs() {
   //set preferences of library style
   lm_libStyle = prefs.getCharPref("libStyle");

   //set preferences where to grab lyrics
   lm_webLoc = prefs.getCharPref("webLoc");

   //set preferences on how to handle saving
   lm_saveLyrics = prefs.getCharPref("saveLyrics");

   //set notify preferences if no lyrics found
   lm_noLyrFound = prefs.getCharPref("noLyrFound");

   //set if Album Name should be displayed
   lm_dispAlbum = prefs.getBoolPref("dispAlbum");
   
   //set if Artist Name should be displayed
   lm_dispArtist = prefs.getBoolPref("dispArtist");
   
   //set if Track Name should be displayed
   lm_dispTrack = prefs.getBoolPref("dispTrack");


   //set CSS link
   var lm_iframe = document.getElementById('lm-content');
   var CSS_defined = lm_iframe.contentWindow
                              .document.getElementById('define_CSS');

   lm_CSS = prefs.getCharPref("styleSheet");

   CSS_defined.setAttribute("href", lm_CSS);
   
   lm_showNotifs = prefs.getBoolPref("showNotifs");
   
   if (lm_showNotifs) {
     ourDisplayPane.contentIcon =
                   "chrome://lyricmaster/content/images/notes.png";
   } else {
     ourDisplayPane.contentIcon =
                   "chrome://lyricmaster/content/images/nonotes.png";
   }

}

var watchPrefs = {
  init: function() {
    prefs.addObserver("", this, false );
  },

  observe: function() {
    setPrefs();
  },

  shutdown: function() {
    prefs.removeObserver("", this);
  }
};

var myPlaylistPlaybackServiceListener = {
 init: function() {
   gMM.addListener(this);
 },

 onMediacoreEvent: function(ev) {
   switch (ev.type) {
     case Ci.sbIMediacoreEvent.TRACK_CHANGE:
       this.onTrackChange(ev.data);
       break;
     case Ci.sbIMediacoreEvent.STREAM_STOP:
     case Ci.sbIMediacoreEvent.STREAM_END:
       this.onStop();
       break;
     default:
       break;
   }
 },

 onTrackChange: function(aMediaItem, aMediaView, aIndex) {
   // Don't do stuff for video
   if (aMediaItem.getProperty(SBProperties.contentType) == "video")
     return;

   if (!myPlaylistPlaybackServiceListener._playing) {
     // If it started out visible, then unhide it
     if (!myPlaylistPlaybackServiceListener._dpHidden)
       ourDisplayPane.collapsed = false;
     myPlaylistPlaybackServiceListener._playing = true;
   }
   var medItm = aMediaItem;
   curMediaItem = medItm;
   showInfo(medItm);
 },

 onStop: function() {
   Lyricmaster.PaneController.lmDeck.selectedIndex = 0;
   ourDisplayPane.collapsed = true;
   myPlaylistPlaybackServiceListener._playing = false;
 },

 onBeforeTrackChange: function() {
 },

 onViewChange: function() {
 },

 onBeforeViewChange: function() {
 },
 
 onTrackIndexChange: function() {
 }

};



function notificationCallback(notificationElement, notifcationButton) {
    gBrowser.loadOneTab(searchURL);
  }


function writeID3(mediaItem){

	var mediaItemArray = Cc["@songbirdnest.com/moz/xpcom/threadsafe-array;1"].createInstance(Ci.nsIMutableArray);

	mediaItemArray.appendElement(mediaItem, false);
        
	if (mediaItemArray.length > 0) {
		var metadataService = Cc["@songbirdnest.com/Songbird/FileMetadataService;1"].getService(Ci.sbIFileMetadataService);
 
		// This will write out the properties in propArray for each item.
		var propArray = ArrayConverter.stringEnumerator([SBProperties.lyrics]);
		metadataService.write(mediaItemArray, propArray);
       }
 

}

function saveLyrics(notificationElement, notifcationButton, mediaItem, lyrics) {
    mediaItem.setProperty("http://songbirdnest.com/data/1.0#lyrics", lyrics);
    writeID3(mediaItem);


  }
  
function addNotification(notificationBoxElement, notificationPriority, mediaItem, lyrics) {
    var mTop = document.getElementById(notificationBoxElement);
    
    var notificationValue = notificationPriority;
    var notificationImage = "images/notif.png";
    if (notificationPriority == 3){
	    var notificationButtons = [{accessKey: null, callback: function (notificationElement, notifcationButton) {saveLyrics(notificationElement, notifcationButton, mediaItem, lyrics)}, label: bigyes, popup: null}]
	    var notificationLabel = asktosave;
	    }
    else {	
    	    var notificationButtons = [{accessKey: null, callback: notificationCallback, label: websearch, popup: null}]
    	    var notificationLabel = lyrnotfound;
            }
    
    mTop.removeAllNotifications(true);
    mTop.appendNotification(notificationLabel,
                            notificationValue,
                            notificationImage,
                            notificationPriority,
                            notificationButtons);
  }

function parseLyrics(artist, album, track, lyrics, mediaItem) {
  var updatedLyrics = lyrics.replace(/<br \/>/g,"");

  buildPage(artist, album, track, updatedLyrics);

  if (lm_saveLyrics == "PROMPT"){
    if (lm_showNotifs)
    {
      addNotification("infobar", 3, mediaItem, updatedLyrics);
    }
  }

  if (lm_saveLyrics == "ALWAYSAVE"){
    saveLyrics("", "", mediaItem, updatedLyrics);
  }

}



function updateLyrics(artist, album, track, mediaItem) {
  // Don't proceed if we don't have valid metadata
  if (!artist || !track)
    return;

  var edit_artist2 = artist.split(" (");
  if (edit_artist2.length>1)
  {
    artist = edit_artist2[0];
  }
  var edit_track = track.split(" (");
  var search_track;
  if(edit_track.length>1) {
    search_track = edit_track[0];
  } else if(edit_track.length<=1) {
    search_track = track;
  }
  if (lm_libStyle == "DOEJ"){
    edit_artist = artist.split(", ");
    artist = edit_artist[1] + " " +edit_artist[0];
  }

  var req = new XMLHttpRequest();
  var _artist = encodeURIComponent(artist);
  var _search_track = encodeURIComponent(search_track);

  if (lm_webLoc == "LWIKI"){
    var url = "http://lyricwiki.org/api.php?artist=" + _artist + "&song=" + _search_track + "&fmt=text";
  }

  if (lm_webLoc == "LPLUGIN"){
    var url = "http://www.lyricsplugin.com/wmplayer03/plugin/?title=" + _search_track + "&artist=" + _artist;
  }


  searchURL = "http://www.google.com/search?q=lyrics+\"" + _search_track + "\"+by+\""+ _artist + "\"";

  window.scrollTo(0,0);
  req.open("GET", url, true);
  req.onreadystatechange = function() {
    if (this.readyState != 4)
      return;
    if (this.status == 200) {
      var respLyr = this.responseText;

      if (lm_webLoc == "LPLUGIN")
      {
	// Initial lookup is done, now emulate the lyricsplugin.com js
	// redirect making sure to include the timestamp and ID
	var jsredirect = respLyr.split("javascript:getContent");
	var inputargchunk = jsredirect[1].split("\)");
	var inputargs = inputargchunk[0].replace(/'/g, "")
					.replace(/\(/g, "")
					.replace(/ /g, "");
	var params = inputargs.split(",");
	var returnartist = params[0];
	var returntitle = params[1];
	var timestamp = params[2];
	var id = params[3];

	var url = "http://www.lyricsplugin.com/wmplayer03/plugin/content.php?"
			+ "artist=" + returnartist
			+ "&title=" + returntitle
			+ "&time=" + timestamp
			+ "&hash=" + id;
	// The referer must be spoofed otherwise lyrics will not be
	// included in the response
	var referer = "http://www.lyricsplugin.com/wmplayer03/plugin/?"
			+ "title=" + returntitle + "&artist=" + returnartist;

	req.open("GET", url, true);
	req.setRequestHeader("Referer", referer);
	req.onreadystatechange = function() {
		if (this.readyState == 4 || this.readyState == "complete")
		{
			var respLyr = this.responseText;
			respLyrResult = respLyr.split("<div id=\"lyrics\">");
			lyrDiv = respLyrResult[1].split("</div>");
			respLyr = lyrDiv[0];
			respLyr = respLyr.replace(/\n/, "");

			_checkResponseAndBuildPage(artist, album, track, respLyr, mediaItem);
		}
	}

	req.send(null);
      }
      else
      {
	// lm_webLoc != "LPLUGIN"
	_checkResponseAndBuildPage(artist, album, track, respLyr, mediaItem);
      }
    } 
  }
  req.send(null);
}

function _checkResponseAndBuildPage(artist, album, track, respLyr, mediaItem)
{
	if (respLyr.length < 10)
	{
		var lyrics = "";
		if (curMediaItem == mediaItem)
		{
			buildPage(artist, album, track, lyrics);
			if (lm_noLyrFound == "NOTIFY")
			{				
				if(lm_showNotifs)
					addNotification("infobar", 3,"","");
			}
		}
	}
	else
	{
		if (curMediaItem == mediaItem)
			parseLyrics(artist, album, track, respLyr, mediaItem);
	}
}

function buildPage(artist, album, track, lyrics){
        
    lyrics = lyrics.replace(/\n/g,"<br>");
    var content_lyric_html = "";

//  The following HTML and its CSS companion files are written by Gege from the MediaMonkey forums,  His addon for MediaMonkey (http://www.mediamonkey.com/forum/viewtopic.php?t=22624) is the inspiration for Lyricmaster.  Thanks Gege!!!
    content_lyric_html = content_lyric_html + "  <table border=0 width=100% cellspacing=0 cellpadding=0>";
   if (lm_dispTrack){
    content_lyric_html = content_lyric_html + "      <tr>";
    content_lyric_html = content_lyric_html + "       <td valign=top>";
    content_lyric_html = content_lyric_html + "        <p class=\"header\"> &nbsp; </p>";
    content_lyric_html = content_lyric_html + "       </td>";
    content_lyric_html = content_lyric_html + "      </tr>";

// TrackNumber = ""
// If ShowTrackNumber = True Then
//  TrackNumber = Sng.TrackOrder & ". "
// End If

   
    content_lyric_html = content_lyric_html + "      <tr>";
    content_lyric_html = content_lyric_html + "        <td valign=top>";
    content_lyric_html = content_lyric_html + "         <h1 id='lyricmaster_title'>" + track + "</h1>";
    content_lyric_html = content_lyric_html + "        </td>";
    content_lyric_html = content_lyric_html + "      </tr>";


    content_lyric_html = content_lyric_html + "      <tr>";
    content_lyric_html = content_lyric_html + "       <td valign=top>";
    content_lyric_html = content_lyric_html + "        <p class=\"separator1\"> &nbsp; </p>";
    content_lyric_html = content_lyric_html + "       </td>";
    content_lyric_html = content_lyric_html + "      </tr>";
   }

  if (lm_dispArtist){
    content_lyric_html = content_lyric_html + "      <tr>";
    content_lyric_html = content_lyric_html + "       <td valign=top>";
    content_lyric_html = content_lyric_html + "        <h2 id='lyricmaster_artist'>" + artist + "</h2>";
    content_lyric_html = content_lyric_html + "       </td>";
    content_lyric_html = content_lyric_html + "      </tr>";
  }


  if (lm_dispAlbum){  
    content_lyric_html = content_lyric_html + "      <tr>";
    content_lyric_html = content_lyric_html + "       <td valign=top>";
    content_lyric_html = content_lyric_html + "        <h3 id='lyricmaster_album'>" + album + "</h3>";
    content_lyric_html = content_lyric_html + "       </td>";
    content_lyric_html = content_lyric_html + "      </tr>";
    }

 //If showYear = True Then
 // songYear = GetYear(Sng.OriginalYear,Sng.Year)
 // If Not songYear = "" Then
 //   content_lyric_html = content_lyric_html + "      <tr>"
 //   content_lyric_html = content_lyric_html + "       <td valign=top>"
 //   content_lyric_html = content_lyric_html + "        <h4>(" & songYear & ")</h4>"
 //   content_lyric_html = content_lyric_html + "       </td>"
 //   content_lyric_html = content_lyric_html + "      </tr>"
 // End If
 //End If

 //If showComposer = True Then
 // If Not Sng.Author & Sng.Lyricist="" Then
 //        If Sng.Author="" Then
 //         w=Sng.Lyricist
 //    ElseIf Sng.Lyricist="" Then
 //         w=Sng.Author
 //    Else:w=Sng.Author & ";" & Sng.Lyricist
 //    End If
 //   content_lyric_html = content_lyric_html + "      <tr>"
 //   content_lyric_html = content_lyric_html + "       <td valign=top>"
 //   content_lyric_html = content_lyric_html + "         <h5>(" & FixMultipleValues(w) & ")</h5>"
 //   content_lyric_html = content_lyric_html + "        </td>"
 //   content_lyric_html = content_lyric_html + "      </tr>"
 // End If
 //End If

  if ((lm_dispAlbum) || (lm_dispArtist) || (lm_dispTrack)){
    content_lyric_html = content_lyric_html + "      <tr>";
    content_lyric_html = content_lyric_html + "       <td valign=top>";
    content_lyric_html = content_lyric_html + "        <p class=\"separator2\"> &nbsp; </p>";
    content_lyric_html = content_lyric_html + "       </td>";
    content_lyric_html = content_lyric_html + "      </tr>";
  }

    if (lm_webLoc == "LPLUGIN")
    {
	// Hide the tunerankings link that now appears
	lyrics = lyrics.replace(/<a href=\"http:\/\/www.tunerankings.com\/\" target=\"_blank\">www.tunerankings.com<\/a>/, "");
    }

    content_lyric_html = content_lyric_html + "      <tr>";
    content_lyric_html = content_lyric_html + "       <td>";
    content_lyric_html = content_lyric_html + "        <p class='lyricmaster_lyrics'>" + lyrics + "</p>";
    content_lyric_html = content_lyric_html + "       </td>";
    content_lyric_html = content_lyric_html + "      </tr>";


 //If ShowComments = True Then
 //    CommentsTxt=HtmlMarkup(Sng.Comment)
 //   If Not CommentsTxt = "" Then
 //   If showLyrics = True Then
 //     content_lyric_html = content_lyric_html + "      <tr>"
 //     content_lyric_html = content_lyric_html + "       <td valign=top>"
 //     content_lyric_html = content_lyric_html + "        <p class=""separator3""> &nbsp; </p>"
 //     content_lyric_html = content_lyric_html + "       </td>"
 //     content_lyric_html = content_lyric_html + "      </tr>"
 //   End If

 //   content_lyric_html = content_lyric_html + "      <tr>"
 //   content_lyric_html = content_lyric_html + "       <td>"
 //   content_lyric_html = content_lyric_html + "        <p>" & CommentsTxt & "</p>"
 //   content_lyric_html = content_lyric_html + "       </td>"
 //   content_lyric_html = content_lyric_html + "      </tr>"
 //   End If
 //End If

    content_lyric_html = content_lyric_html + "      <tr>";
    content_lyric_html = content_lyric_html + "       <td valign=top>";
    content_lyric_html = content_lyric_html + "        <p class=\"footer\"> &nbsp; </p>";
    content_lyric_html = content_lyric_html + "       </td>";
    content_lyric_html = content_lyric_html + "      </tr>";
    content_lyric_html = content_lyric_html + "  </table>";

    document.getElementById('lm-content').contentWindow.document.body.innerHTML = content_lyric_html;

}



function showInfo(mediaItem) {

// make sure the deck is showing our active playing vbox
if (Lyricmaster.PaneController.lmDeck.selectedIndex != 1)
	Lyricmaster.PaneController.lmDeck.selectedIndex = 1;

var metadataLyrics = mediaItem.getProperty("http://songbirdnest.com/data/1.0#lyrics");

var notifRem = document.getElementById("infobar");
notifRem.removeAllNotifications(true);


//var displayPane = mainDoc.getElementById("displaypane_right_sidebar");
//var paneHeight = displayPane.boxObject.height;

//if (paneHeight != capturedHeight) {
//	capturedHeight = paneHeight;
//	paneHeight = (((paneHeight - 170) / 13) - 0);
//	document.getElementById('lyrics').setAttribute("rows", paneHeight);
//	}

//document.getElementById('lyrics').value="";
//document.getElementById('lyrics').className="turn_off";

document.getElementById('lm-content').contentWindow.document.body.innerHTML = "";

var metadataArtist = mediaItem.getProperty(SBProperties.artistName);
var metadataAlbum = mediaItem.getProperty(SBProperties.albumName);
var metadataTrack = mediaItem.getProperty(SBProperties.trackName);

if (metadataAlbum == null){
    metadataAlbum = "";    
}
/*
var metadataArtist = Components.classes["@songbirdnest.com/Songbird/DataRemote;1"].createInstance(Components.interfaces.sbIDataRemote);
metadataArtist.init("metadata.artist", null);

var metadataAlbum = Components.classes["@songbirdnest.com/Songbird/DataRemote;1"].createInstance(Components.interfaces.sbIDataRemote);
metadataAlbum.init("metadata.album", null);

var metadataTrack = Components.classes["@songbirdnest.com/Songbird/DataRemote;1"].createInstance(Components.interfaces.sbIDataRemote);
metadataTrack.init("metadata.title", null);
*/

if (metadataLyrics != null)
     {
     buildPage(metadataArtist, metadataAlbum, metadataTrack, metadataLyrics);
     //buildPage(metadataArtist.stringValue, metadataAlbum.stringValue, metadataTrack.stringValue, metadataLyrics);

     }
else {
     
     updateLyrics(metadataArtist, metadataAlbum, metadataTrack, mediaItem);
     //updateLyrics(metadataArtist.stringValue, metadataAlbum.stringValue, metadataTrack.stringValue, mediaItem);
     }




}

function LM_checkContext(){
        
        var selected = document.getElementById('lm-content').contentWindow.getSelection();
        selected = String(selected);
        
        if (selected.length > 0)
        {
                document.getElementById("copyMenuItem").disabled = false;
        }
        
        if (selected.length < 1)
        {
                document.getElementById("copyMenuItem").disabled = true;
        }
        
        if (gMM.status.state != Ci.sbIMediacoreStatus.STATUS_PLAYING)
	{
               document.getElementById("metadataMenuItem").disabled = true;
               document.getElementById("refreshMenuItem").disabled = true;
               document.getElementById("clearMenuItem").disabled = true;
        }
        else if (gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PLAYING)
	{
               document.getElementById("metadataMenuItem").disabled = false;
               document.getElementById("refreshMenuItem").disabled = false;
               document.getElementById("clearMenuItem").disabled = false;
        }
}

function LM_Contextrefresh(){

        if ((gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PLAYING) ||
			(gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PAUSED) ||
			(gMM.status.state == Ci.sbIMediacoreStatus.STATUS_BUFFERING))
	{
		var view = gMM.sequencer.view;
		if (view) {
			var i = view.getItemByIndex(gMM.sequencer.viewPosition);
			showInfo(i);
		}
	}
}

function LM_Contextclear()
{
                if ((gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PLAYING) ||
			(gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PAUSED) ||
			(gMM.status.state == Ci.sbIMediacoreStatus.STATUS_BUFFERING))
	{
                curMediaItem.setProperty("http://songbirdnest.com/data/1.0#lyrics", null);
                curMediaItem.setProperty("http://songbirdnest.com/data/1.0#hasLyrics", null);
                var artist = curMediaItem.getProperty(SBProperties.artistName);
                var album = curMediaItem.getProperty(SBProperties.albumName);
                var track = curMediaItem.getProperty(SBProperties.trackName);
                writeID3(curMediaItem);
                buildPage(artist, album, track, "");
        }
}

function LM_setCurPlayToSel(){
        
        var mediacoreManager = Cc["@songbirdnest.com/Songbird/Mediacore/Manager;1"].getService(Ci.sbIMediacoreManager);
        
        if (mediacoreManager.sequencer.viewPosition >= 0)
        {
           var mediaView = mediacoreManager.sequencer.view;
           var trackIndex = mediacoreManager.sequencer.viewPosition;
           var mediaTab = gBrowser.getTabForView(mediaView);
           if (mediaTab) {
           if (mediaTab.mediaPage) {
               mediaTab.mediaPage.highlightItem(trackIndex);
             } else if (mediaTab.outerPlaylist) {
               var tree = mediaTab.outerPlaylist.tree;
               tree.treeBoxObject.ensureRowIsVisible(trackIndex);
               tree.view.selection.select(trackIndex);
             }
           }
        }
}

function LM_copyToClip() {

  var selected = document.getElementById('lm-content').contentWindow.getSelection();
  var ClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"] .getService(Components.interfaces.nsIClipboardHelper);
  ClipboardHelper.copyString(selected); 

}

function LM_goDoCommand(command)
{
  LM_setCurPlayToSel();
  var controller =
      top.document.commandDispatcher.getControllerForCommand(command);
  if (controller && controller.isCommandEnabled(command))
    controller.doCommand(command);
}

/**
 * Controller for pane.xul
 */
Lyricmaster.PaneController = {
  onLoad: function() {
    document.addEventListener("unload", function(e) {
        Lyricmaster.PaneController.onUnLoad(e);
    }, false);
    
    this._initialized = true;
    
    // Make a local variable for this controller so that
    // it is easy to access from closures.
    var controller = this;

    var displayPaneManager =
            Cc["@songbirdnest.com/Songbird/DisplayPane/Manager;1"]
              .getService(Ci.sbIDisplayPaneManager);
    var dpInstantiator = displayPaneManager.getInstantiatorForWindow(window);
    if (dpInstantiator)
    {
      ourDisplayPane = dpInstantiator.displayPane;
      myPlaylistPlaybackServiceListener._dpHidden = ourDisplayPane.collapsed;
    }

    if (prefs.getBoolPref("showNotifs")) {
      document.getElementById("notifEnabledMenuItem").setAttribute("checked",
                                                                   "true");
      document.getElementById("notifDisabledMenuItem").setAttribute("checked",
                                                                    "false");
    } else {
      document.getElementById("notifEnabledMenuItem").setAttribute("checked",
                                                                   "false");
      document.getElementById("notifDisabledMenuItem").setAttribute("checked",
                                                                    "true");
    }
    myPlaylistPlaybackServiceListener.init();
    setPrefs();
    watchPrefs.init();

    // Save a pointer to our deck
    this.lmDeck = document.getElementById("lm-deck");

    // Check to see if we're already playing something
    if ((gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PLAYING) ||
        (gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PAUSED) ||
        (gMM.status.state == Ci.sbIMediacoreStatus.STATUS_BUFFERING))
    {
      myPlaylistPlaybackServiceListener._playing = true;
      var view = gMM.sequencer.view;
      if (view) {
        var i = view.getItemByIndex(gMM.sequencer.viewPosition);
        showInfo(i);
      }
    } else {
      myPlaylistPlaybackServiceListener._playing = false;
      ourDisplayPane.collapsed = true;
    }
  },
  


  /**
   * Called when the pane is about to close
   */
  onUnLoad: function() {
    this._initialized = false;
    watchPrefs.shutdown();
    gMM.removeListener(myPlaylistPlaybackServiceListener);
  },
  
  /**
   * Load the Display Pane documentation in the main browser pane
   */
  loadHelpPage: function() {
    // Ask the window containing this pane (likely the main player window)
    // to load the display pane documentation
    top.loadURI("http://songbirdnest.com/add-on-api/articles/display-panes");
  }
  
};

